import datetime
import uuid

from fastapi import APIRouter, HTTPException

from config.common_config import DATABASE_CONFIG
from models.request_models import SearchRequest, SearchResponse, SaveChatRequest, SaveChatResponse
from models.chat_record import ChatRecord, ContentType, Role
from database.milvus_client import MilvusClient
from database.embedding_model import EmbeddingModel
from models.workflow.inputModel import InputModel
from server.chat_record_server import ChatRecordServer
from workflows.chatFlow import ChatFlow

router = APIRouter(prefix="/api/v1", tags=["chat"])

# 初始化组件
chat_record_server = ChatRecordServer(
    host=DATABASE_CONFIG["HOST"],
    port=DATABASE_CONFIG["PORT"],
    user=DATABASE_CONFIG["USER"],
    pwd=DATABASE_CONFIG["PASSWORD"]
)
embedding_model = EmbeddingModel()
import logging

chatFlow = ChatFlow()

logger = logging.getLogger(__name__)

@router.post("/search_chat_history", response_model=SearchResponse)
async def search_chat_history(request: SearchRequest):
    rId= str(uuid.uuid4())
    print("查询聊天开始"+rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    try:
        logger.info("查询用户ID"+request.userId)
        query_embedding = embedding_model.get_embedding(request.keyWord)
        #print(query_embedding.shape)
        records = chat_record_server.search_records(
            saas_id=request.saasId,
            user_id=request.userId,
            query_embedding=query_embedding,
            content_type=request.contentType,
            role=request.role,
            top_k=request.topk,
            alpha = request.alpha,
            min_score = request.min_score
        )

        if not records:
            return SearchResponse(chatHistory="没有找到相关聊天记录")

        chat_history = []
        for r in records:
            content= f"{r['content']}"
            # content = f"{r['role']}: {r['content']}"
            if r['content_des']:
                content += f" (描述: {r['content_des']})"
            chat_history.append(content)
        print("查询聊天开始" + rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return SearchResponse(chatHistory="\n\n".join(chat_history))

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/save_chat_record", response_model=SaveChatResponse)
async def save_chat_record(request: SaveChatRequest):
    rId = str(uuid.uuid4())
    print("新增开始" + rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    try:
        record = ChatRecord(
            saas_id=request.saasId,
            user_id=request.userId,
            content_type=request.contentType,
            content=request.content,
            role=request.role,
            content_des=request.contentDes
        )

        embedding = embedding_model.get_embedding(record.chat_content)
        start = record.content.find("user:") + len("user:")
        end = record.content.find("assistant:")
        extracted_chat = record.content[start:end]
        chat_embedding = embedding_model.get_embedding(extracted_chat)
        record_id = chat_record_server.insert_record(record,embedding,chat_embedding)
        print("新增结束" + rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return SaveChatResponse(
            status="success",
            recordId=record_id
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/start_chat_flow", response_model=InputModel)
async def start_chat_flow(request: InputModel):

    str= chatFlow.chat(request.userId,request.content)

    return str
